<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Models\Comment;
use App\Models\Good;
use App\Transformers\CommentsTransformer;
use Illuminate\Http\Request;

class CommentController extends BaseController
{
    /**
     * 评价列表
     */
    public function index(Request $request)
    {
        //搜索条件
        $rate = $request->input('rate', 0);
        $goods_title = $request->input('goods_title', '');

        $comments = Comment::when($rate, function($query) use ($rate) {
            $query->where('rate', $rate);
        })->when($goods_title, function($query) use ($goods_title) {
            $goods_id = Good::where('title', 'like', '%' . $goods_title . '%')->pluck('id');
            $query->whereIn('goods_id', $goods_id);
        })
                           ->paginate(1);
        return $this->response->paginator($comments, new CommentsTransformer());
    }

    /**
     * 评价的详情
     */
    public function show(Comment $comment)
    {
        return $this->response->item($comment, new CommentsTransformer());
    }

    /**
     *  商家回复
     */
    public function reply(Request $request, Comment $comment)
    {
        $request->validate([
                               'reply' => 'required|string|max:255',
                           ], [
                               'reply.required' => '回复不能为空',
                               'reply.max'      => '回复不能超过255个字符',
                           ]);
        $comment->reply = $request->input('reply');
        $comment->save();
        return $this->response->noContent();
    }
}
